<template>
  <!-- 资产型号表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="750px"
    draggable
    @close="closeDialog"
    destroy-on-close
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100"
      v-show="!props.isReadonly"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="文档编号" prop="docNo">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.docNo"
              placeholder="请输入文档编号"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="文档名称" prop="docName">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.docName"
              placeholder="请输入文档名称"
              clearable
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="产品" prop="productCode">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.productCode"
              placeholder="请选择产品"
              style="width: 300px"
              clearable
            >
              <el-option
                v-for="item in productList"
                :key="`${item.materialCode}`"
                :label="`${item.materialName}`"
                :value="`${item.materialCode}`"
              />
            </el-select>

            <span v-else>{{ formData.materialName }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="文档分类" prop="docKind">
            <el-select
              style="width: 100%"
              v-if="!props.isReadonly"
              v-model="formData.docKind"
              placeholder="文档分类"
              clearable
            >
              <el-option
                v-for="item in dictionaryStore.filterDictList(
                  'docCategorization'
                )"
                :key="item.value"
                :label="item.label"
                :value="Number(item.value)"
              />
            </el-select>

            <span v-else>{{
              dictionaryStore.filterDictName(
                "docCategorization",
                formData.docKind
              )
            }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="文档版本号" prop="docVersionNo">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.docVersionNo"
              placeholder="请输入文档版本号"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="关键字" prop="keyword">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.keyword"
              placeholder="请输入关键字"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="排序" prop="sort">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.sort"
              placeholder="请输入排序"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="props.docType == '2'">
          <el-form-item label="存储位置" prop="path">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.path"
              placeholder="请输入位置"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="props.docType == '2' ? 12 : 24">
          <el-form-item label="备注" prop="remarks">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.remarks"
              placeholder="请输入备注"
              clearable
            />

            <span v-else>{{ formData.remarks }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="props.docType == '1'">
          <el-row class="ml-[15px]">
            <moldgeneraldocument-upload
              :multiple="false"
              :isRead="props.isReadonly"
              :files="formData.image"
              @update-files="updateFormFiles"
            />
          </el-row>
        </el-col>
      </el-row>
    </el-form>
    <el-descriptions
      v-show="props.isReadonly"
      class="margin-top"
      title=""
      :column="2"
      size="large"
      border
    >
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">文档编号</div>
        </template>

        <div style="width: 100%; word-break: break-all">
          {{ formData.docNo }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">文档名称</div>
        </template>

        <div style="width: 100%; word-break: break-all">
          {{ formData.docName }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">设备种类</div>
        </template>

        <div style="width: 100%; word-break: break-all">
          {{ getAssetTypeName(formData.assetTypeId) }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">产品</div>
        </template>
        {{ formData.productName }}
      </el-descriptions-item>

      <el-descriptions-item>
        <template #label>
          <div class="cell-item">文档分类</div>
        </template>

        {{
          dictionaryStore.filterDictName("docCategorization", formData.docKind)
        }}
      </el-descriptions-item>

      <el-descriptions-item>
        <template #label>
          <div class="cell-item">文档版本号</div>
        </template>
        {{ formData.docVersionNo }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">关键字</div>
        </template>
        {{ formData.keyword }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">排序</div>
        </template>
        {{ formData.sort }}
      </el-descriptions-item>
      <el-descriptions-item v-if="props.docType == '2'">
        <template #label>
          <div class="cell-item">存储位置</div>
        </template>
        {{ formData.path }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">备注</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.remarks || "暂无备注" }}
        </div>
      </el-descriptions-item>
    </el-descriptions>
    <div v-if="props.docType == '1' && props.isReadonly">
      <generaldocument-upload
        v-if="formData.image.length > 0"
        :isRead="props.isReadonly"
        :files="formData.image"
        @update-files="updateFormFiles"
      />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "EQUDEVICEMODELEDITE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  docType: {
    type: String,
    default: () => {
      return "";
    },
  },
  assetTypeId: {
    type: String,
    default: () => {
      return "";
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    if (props.assetTypeId) {
      formData.assetTypeId = props.assetTypeId;
      catalogList.value.forEach((item) => {
        if (item.id == props.assetTypeId) {
          formData.assetTypeName = item.assetTypeName;
          formData.assetTypeCode = item.assetTypeCode;
          return;
        } else {
          if (item.nodes.length > 0) {
            catalogList1(item.nodes);
          }
        }
      });
    }
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);
const catalogList1 = (item) => {
  if (item.length > 0) {
    item.forEach((item1) => {
      if (item1.id == props.assetTypeId) {
        formData.assetTypeName = item1.assetTypeName;
        formData.assetTypeCode = item.assetTypeCode;
        return;
      } else {
        catalogList1(item1.nodes);
      }
    });
  }
};
const rules = reactive({
  assetKind: [],
  assetTypeId: [
    {
      required: true,
      message: "请选择模具类型",

      trigger: "change",
    },
  ],

  // version: [
  //   {
  //     required: true,
  //     message: "请选择品牌",
  //     pattern: "[^ \x20]+",
  //     trigger: "change",
  //   },
  // ],
  docNo: [
    {
      required: true,
      message: "请输入文档编号",
      pattern: "[^ \x20]+",
      trigger: "blur",
    },
    {
      min: 1,
      max: 50,
      message: "长度在 1 到 50 个字符",

      trigger: "blur",
    },
    { required: true, message: "请输入文档编号", trigger: "blur" },
  ],
  docName: [
    { min: 1, max: 128, message: "长度在 1 到 128 个字符", trigger: "blur" },
    {
      required: true,
      message: "请输入文档名称",
      pattern: "[^ \x20]+",
      trigger: "blur",
    },
  ],
  // makerId: [{ required: true, message: "请选择制造商", trigger: "change" }],
  remarks: [
    {
      min: 1,
      max: 255,
      message: "长度在 1 到 255 个字符",
      pattern: "[^ \x20]+",
      trigger: "blur",
    },
  ],
  // assetModelId: [
  //   { required: true, message: "请选择品牌型号", trigger: "change" },
  // ],
  // docKind: [{ required: true, message: "请选择文档分类", trigger: "change" }],
  docVersionNo: [
    // {
    //   required: true,
    //   message: "请输入文档版本号",
    //   pattern: "[^ \x20]+",
    //   trigger: "blur",
    // },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  keyword: [
    // {
    //   required: true,
    //   message: "请输入关键字",
    //   pattern: "[^ \x20]+",
    //   trigger: "blur",
    // },
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  sort: [
    // { required: true, message: "请输入排序", trigger: "blur" },
    // {
    //   required: true,
    //   pattern: "[^ \x20]+",
    //   message: "请输入排序",
    //   trigger: "blur",
    // },
    // { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
    {
      validator: validateDegree,
      trigger: "blur",
    },
  ],
  lastUpdatedUserId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  lastUpdatedUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  enabled: [],
  deleted: [],
});
function validateDegree(rule: any, value: any, callback: (a?: any) => {}) {
  if (isNaN(parseFloat(value)) && isFinite(value)) {
    callback(new Error("请输入整数"));
  } else if (!/^[+-]?\d+?(e[+-]?\d+)?$/.test(value)) {
    callback(new Error("请输入整数"));
  } else if (Number(value) < 0) {
    callback(new Error("请输入大于0的整数"));
  } else {
    callback();
  }
}
const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  productCode: "",
  productName: "",

  version: "",
  assetKind: "",
  assetTypeId: "",
  assetTypeName: "",
  assetTypeCode: "",
  makerId: "",
  makerName: "",
  makerCode: "",
  assetModelId: "",
  assetModelNo: "",
  assetBrandId: "",
  assetBrandName: "",
  brandId: "",
  brandName: "",
  brandCode: "",
  modelNo: "",
  remarks: "",
  organizationId: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: 1,
  deleted: "",
  docType: "1",

  docNo: "",
  docName: "",

  docVersionNo: "",
  keyword: "",
  docKind: "",
  sort: "",
  fileType: "",
  path: "",
  originalFilename: "",
  fileName: "",
  url: "",
  image: [],
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        productCode,
        productName,
        version,
        assetKind,
        assetTypeId,
        assetTypeName,
        assetTypeCode,
        assetModelId,
        assetModelNo,
        assetBrandId,
        assetBrandName,
        makerCode,
        makerId,
        makerName,
        brandId,
        brandName,
        brandCode,
        modelNo,
        remarks,
        organizationId,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
        docNo,
        docName,
        docType,
        docVersionNo,
        keyword,
        docKind,
        sort,
        fileType,
        path,
        originalFilename,
        fileName,
        url,
      } = newVal;
      Object.assign(formData, {
        id,
        productCode,
        productName,
        version,
        assetKind,
        assetTypeId,
        assetTypeName,
        assetTypeCode,
        assetModelId,
        assetModelNo,
        assetBrandId,
        assetBrandName,
        makerId,
        makerName,
        makerCode,
        brandId,
        brandCode,
        brandName,
        modelNo,
        remarks,
        organizationId,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
        docNo,
        docName,
        docType,
        docVersionNo,
        keyword,
        docKind,
        sort,
        fileType,
        path,
        originalFilename,
        fileName,
        url,
      });
      formData.assetKind = "3";
      formData.sort = String(sort);
      //  编辑时获取品牌型号数据
      if (formData.url) {
        formData.image.push({
          fileType: formData.fileType,
          originalfilename: formData.originalFilename,
          filename: formData.fileName,
          path: formData.path,
          url: formData.url,
          //       formData.fileType = val[0].fileType;
          // formData.fileName = val[0].filename;
          // formData.originalFilename = val[0].originalfilename;
          // formData.path = val[0].path;
          // formData.url = val[0].url;
        });
      }
    }
  }
);
watch(
  () => props.docType,
  (newVal: any) => {
    console.log("newVal", newVal);

    formData.docType = newVal;
  }
);
/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false, formData.docType);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.productCode = "";
  formData.productName = "";
  formData.version = "";
  formData.assetKind = "";
  formData.assetTypeId = "";
  formData.assetTypeName = "";
  formData.assetTypeCode = "";
  formData.assetModelId = "";
  formData.assetModelNo = "";
  formData.assetBrandId = "";
  formData.assetBrandName = "";
  formData.makerId = "";
  formData.makerName = "";
  formData.makerCode = "";
  formData.brandId = "";
  formData.brandName = "";
  formData.brandCode = "";
  formData.modelNo = "";
  formData.remarks = "";
  formData.organizationId = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = 1;
  formData.deleted = "";
  formData.docNo = "";
  formData.docName = "";

  formData.docVersionNo = "";
  formData.keyword = "";
  formData.docKind = "";
  formData.sort = "";
  formData.fileType = "";
  formData.path = "";
  formData.originalFilename = "";
  formData.fileName = "";
  formData.url = "";
  formData.image = [];
}

const loading = ref(false);

/** 资产型号保存提交 */
function handleSubmit() {
  console.log(formData);

  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      formData.assetKind = "3";
      formData.productName = findProduct(formData.productCode);
      await request({
        url: "/eam/eamCommonDoc/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

function findProduct(productCode: String) {
  const product = productList.value.find(
    (item: any) => item.materialCode == productCode
  );
  if (product) {
    return product.materialName;
  }
  return productCode;
}

// 目录树
const catalogList: any = ref([]);

// 获取内容树数据
const getCAtalogList = async () => {
  // 获取内容树
  await request({
    url: "eam/mouldAssetType/getAvailableTree",
    method: "POST",
    data: { assetKind: "3" },
  }).then((res) => {
    catalogList.value = res.data;
  });
};

const handleNodeClick = (e: any) => {
  if (e) {
    formData.assetTypeName = e.assetTypeName;
    formData.assetTypeCode = e.assetTypeCode;

    /** ---扩展参数 获取--- **/
  } else {
    formData.assetTypeName = "";
    formData.assetTypeCode = "";

    /** ---扩展参数 清空--- **/
  }
};

// 查看时获取name
const getAssetTypeName = (id) => {
  if (id) {
    const current =
      catalogList.value?.filter((item: any) => item?.id === id)[0] ?? {};
    return current?.assetTypeName || "";
  } else {
    return "";
  }
};

//获取制造商列表
const makerList: any = ref([]);
const getMakerList = async () => {
  request({
    url: `/eam/eammaker/getList`,
    method: "post",
    data: { assetKind: "3" },
  })
    .then((res) => {
      makerList.value = res.data;
    })
    .catch((res) => {
      console.log(res);
    });
};

// 图片处理
function updateFormFiles(val: []) {
  if (val.length > 0) {
    formData.fileType = val[0].fileType;
    formData.fileName = val[0].filename;
    formData.originalFilename = val[0].originalfilename;
    formData.path = val[0].path;
    formData.url = val[0].url;
  } else {
    formData.fileType = "";
    formData.fileName = "";
    formData.originalFilename = "";
    formData.path = "";
    formData.url = "";
  }
}
onMounted(() => {
  getCAtalogList();
  getMakerList();
  getProductList();
}),
  // 组件销毁时调用
  onBeforeUnmount(() => {
    visibleDialog.value = false;
    emit("change-visible", false);
  });

const productList: any = ref([]);

const getProductList = async () => {
  // 获取内容树
  await request({
    url: "/mdm/mdmmaterial/getList",
    method: "POST",
    data: { materialType: "3" },
  }).then((res) => {
    productList.value = res.data;
  });
};
</script>
<style lange="scss" scoped>
:deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
  width: 110px;
}
:deep(.el-descriptions__content.el-descriptions__cell.is-bordered-content) {
  min-width: 180px;
}
</style>
